<?php

namespace app\modules\m\controllers;

use yii\web\Controller;
use \app\modules\m\controllers\common\BaseController;
use \app\models\book\Book;
use \app\models\member\MemberFav;
use \app\models\member\MemberCart;
use \app\models\user\China;
use \app\models\user\MemberAddress;
use \app\common\services\UtilService;
use \app\common\services\UrlService;
use \app\common\services\PayOrderService;
class ProductController extends BaseController
{
    
    public function actionIndex()
    {
    	
        $kw=trim($this->get("kw",""));
        $sort_field=trim($this->get("sort_field","default"));
        $sort=trim($this->get("sort",""));
        $search_conditions=[
            'kw' => $kw,
            'sort_field' => $sort_field,
            'sort' => $sort
        ];
        $list=$this->getSearchData();
        
        return $this->render('index',['search_conditions'=>$search_conditions,'list'=>$list]);
    }
    public function actionInfo()
    {
    	$this->layout=false;
        $id=$this->get("id","");
        $res=Book::find()->where(['id'=>$id])->one();
        if(!$res){
            return $this->renderJSON([],"操作非法",-1);
        }

        return $this->render('info',['info'=>$res]);
    }
    //订单页面
    public function actionOrder()
    {
        if(\Yii::$app->request->isPost){
            $product_item=$this->post("product_item","");

            $address_id=$this->post("address_id","");

            if(!$product_item){
                return $this->renderJSON([],"请选择商品再提交",-1);
            }
            $book_ids=[];
            foreach($product_item as $v){
                $tmp_item_info=explode('#', $v);
                $book_ids[]=$tmp_item_info[0];
            }
            //indexBy以id为键值
            $book_map=Book::find()->where(['id'=>$book_ids,'status'=>1])->indexBy("id")->asArray()->all();
            if(!$book_map){
                return $this->renderJSON([],"请选择商品再提交",-1);
            }
            //todo下订单
            $items=[];
            $target_type=1;//1代表图书
            foreach ($product_item as $v) {
                //book_id=>quality
                $tmp_items_info=explode("#",$v);
                //定义临时的书籍信息
                $tmp_book_info=$book_map[$tmp_items_info[0]];
                
               $items[]=[
                    'price'=>$tmp_book_info['price']*$tmp_items_info[1],
                    'quantity'=>$tmp_items_info[1],
                    
                    'target_type'=>1,
                    'target_id'=>$tmp_items_info[0],
               ];
            }
            $params = [
            'pay_type' => 1,
            'pay_source' => 2,
            'target_type' => $target_type,
            'note' => '购买书籍',
            'status' => -8,
            'express_address_id' => $address_id
        ];
        $sc=$this->post('sc',"");
        if($sc=='cart'){
            $member=$this->current_user;
            $product_item=$this->post('product_item','');
            $items=[];
            foreach($product_item as $v){
                $tmp_data=explode("#",$v);
                $book=Book::find()->where(['id'=>$tmp_data[0]])->one();
                $items[]=[
                    'price'=>$book->price*$tmp_data[1],
                    'quantity'=>$tmp_data[1],
                    'target_type'=>1,
                    'target_id'=>$tmp_data[0],
                ];
                
                $params=[
                    'pay_type' => 1,
                    'pay_source' => 2,
                    'target_type' =>1,
                    'note' => '购买书籍',
                    'status' => -8,
                    'express_address_id' => 0
                ];
            }
            // var_dump($items);die;
            $res=PayOrderService::createPayOrder($member->id,$items,$params);
                if(!$res){
                    return $this->renderJSON([],"提交失败,失败原因:".PayOrderService::getLastErrorMsg(),-1);
                }
           
        return $this->renderJSON([
                'url'=>UrlService::buildMUrl("/product/order?sc=cart"),
                ],"下单成功,前去支付吧!");
        }
        $cookies = \Yii::$app->request->cookies;
        $member = $cookies->get('member');
        $member=$member->value;
        
            $res=PayOrderService::createPayOrder($member['id'],$items,$params);
            if(!$res){
                return $this->renderJSON([],"提交失败,失败原因:".PayOrderService::getLastErrorMsg(),-1);
            }

            return $this->renderJSON([
                'url'=>UrlService::buildMUrl("/pay/buy?pay_order_id=$res[id]"),
                ],"下单成功,前去支付吧!");
        }
        //get方法
        $id=$this->get('id',"");
    	$quantity=$this->get('quantity',"");
        $sc=$this->get('sc','');
        //如果为购物车
        if($sc=='cart'){

            $member=$this->current_user;

            $res=MemberCart::find()->join('inner join','book','member_cart.book_id=book.id')->where(['member_id'=>$member->id])->select('book.price,book.name,book.main_image,book.id,member_cart.quantity')->asArray()->all();
            //地址
            $list=MemberAddress::find()->where(['member_id'=>$this->current_user->id])->asArray()->all();
            $arr=[];
            foreach($list as $k=>$v){
                $tmp_province=china::find()->select('name')->where(['id'=>$v['province_id']])->one();
                $province=$tmp_province['name'];
                $tmp_city=china::find()->select('name')->where(['id'=>$v['city_id']])->one();
                $city=$tmp_city['name'];
                $tmp_area=china::find()->select('name')->where(['id'=>$v['area_id']])->one();
                $area=$tmp_area['name'];
                $arr[$k]['nickname']=$v['nickname'];
                $arr[$k]['mobile']=$v['mobile'];
                $arr[$k]['id']=$v['id'];
                $arr[$k]['address']=$province.$city.$area.$v['address'];
                $arr[$k]['is_default']=$v['is_default'];
            }
           
            
            return $this->render('order',['product_list'=>$res,'address'=>$arr]);
        }
        if(!$id){
            return $this->renderJSON([],"非法操作",-1);
        }
        if(!$quantity){
            return $this->renderJSON([],"非法操作",-1);
        }
        //查询id是否存在于数据库中
        $is_find=Book::find()->where(['id'=>$id,'status'=>1])->one();
        if(!$is_find){
            return $this->renderJSON([],"书籍不存在",-1);
        }    
        $product_list=[
            [
                'id'=>$is_find['id'],
                'name'=>$is_find['name'],
                'price'=>$is_find['price'],
                'main_image'=>$is_find['main_image'],
                'quantity'=>$quantity,
            ]
        ];
        //地址
        $list=MemberAddress::find()->where(['member_id'=>$this->current_user->id])->asArray()->all();
        $arr=[];
        foreach($list as $k=>$v){
            $tmp_province=china::find()->select('name')->where(['id'=>$v['province_id']])->one();
            $province=$tmp_province['name'];
            $tmp_city=china::find()->select('name')->where(['id'=>$v['city_id']])->one();
            $city=$tmp_city['name'];
            $tmp_area=china::find()->select('name')->where(['id'=>$v['area_id']])->one();
            $area=$tmp_area['name'];
            $arr[$k]['nickname']=$v['nickname'];
            $arr[$k]['mobile']=$v['mobile'];
            $arr[$k]['id']=$v['id'];
            $arr[$k]['address']=$province.$city.$area.$v['address'];
            $arr[$k]['is_default']=$v['is_default'];
        }
        return $this->render('order',['product_list'=>$product_list,'address'=>$arr]);
    }
    //根据字段查找
    public function getSearchData($page_size=4){
        $p=$this->get("p","1");
        $skip=$p*$page_size;
        $kw=trim($this->get("kw",""));
        $sort_field=trim($this->get("sort_field","default"));
        $sort=trim($this->get("sort",""));
        $search_conditions=[
            'kw' => $kw,
            'sort_field' => $sort_field,
            'sort' => $sort
        ];
        $query=Book::find();
        if($kw){
            $tags=['LIKE','tags','%'.$kw.'%',false];
            $name=['LIKE','name','%'.$kw.'%',false];
            $query->andWhere(["OR",$name,$tags]);
        }
        if($sort_field!="default"){
            $query->orderBy([$sort_field=>$sort=='asc'?SORT_ASC:SORT_DESC]);
            
        }else{
            $query->orderBy(['id'=>SORT_DESC]);
        }
        return $query->offset(  ( $p - 1 ) * $page_size )
            ->limit( $page_size )
            ->all();;
    }
    //下拉刷新
    public function actionSearch(){
        $list=$this->getSearchData();
        $data = [];
        if( $list ){
            foreach( $list as $_item ){
                $data[] = [
                    'id' => $_item['id'],
                    'name' => UtilService::encode( $_item['name'] ),
                    'price' => UtilService::encode( $_item['price'] ),
                    'main_image_url' => UrlService::buildPicUrl("book",$_item['main_image'] ),
                    'month_count' => $_item['month_count']
                ];
            }
        }
        return $this->renderJSON([ 'data' => $data ,'has_next' => ( count( $data ) == 4 )?1:0 ] );
    }
    //点击收藏
    public function actionFav(){
        //将商品添加到收藏表中
        $cookie=\Yii::$app->request->cookies;
        $info=$cookie->getValue('member');
        $member_id=$info->id;
        $book_id=$this->post("id","");
        $act=$this->post("act","");
        if(!in_array($act,['set','del'])){
            return $this->renderJSON([],"系统繁忙~,稍后再试",-1);
        }
        //如果为删除收藏
        if($act=='del'){

        }
        //添加到member_fav表
        $new_fav=new Memberfav();
        $new_fav->member_id=$member_id;
        $new_fav->book_id=$book_id;
        $new_fav->created_time=time();
        $new_fav->save(0);
        return $this->renderJSON([],"添加成功");
    }
    //加入购物车
    public function actionCart(){
        $cookie=\Yii::$app->request->cookies;
        $info=$cookie->getValue('member');
        $member_id=$info->id;
        $book_id=$this->post("id","");
        $quantity=$this->post("quantity","");
        $act=$this->post("act","");
        
        //如果为del
        if($act=="del"){
            $book_id=$this->post('book_id',"");
            $member=$this->current_user;
            $res=MemberCart::find()->where(['member_id'=>$member->id,'book_id'=>$book_id])->one();
            if(!$res){
                return $this->renderJson([],"非法操作",-1);
            }
            $res->delete();
            return $this->renderJson([],"删除成功");
        }
        //如果已经存在此商品则商品数量变化就行
        $is_find=MemberCart::find()->where(['member_id'=>$member_id,'book_id'=>$book_id])->one();
        //如果存在
        if($is_find){
            $new_cart=$is_find;
            $new_cart->quantity=$new_cart->quantity+$quantity;
            $new_cart->updated_time=time();

        }else{
            $new_cart=new MemberCart();
            $new_cart->member_id=$member_id;
            $new_cart->book_id=$book_id;
            $new_cart->quantity=$quantity;
            $new_cart->created_time=time();
            $new_cart->updated_time=time();
        }
        $new_cart->save(0);
        return $this->renderJSON([],"添加成功");
    }
}
